const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
import m from "../models/PhoneCode";
import _ from "lodash";
import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";

import utils from "../utils";

const moment = require("moment");

import { isEmail, isPhone, phoneCode, isDebug } from "../config";

import { notuser, pwderr } from "../config";

router.get("/", function(req: Request, res: Response, next: NextFunction) {
  m.find(function(err: any, products: any) {
    if (err) return next(err);
    res.json(products);
  });
});

router.get("/:id/:type/:password", async (req: Request, res: Response, next: NextFunction) => {
  const o: any = {};

  let ret: any = {};

  const isEmail = req.params.type == "1";
  const isPhone = req.params.type == "2";

  if (isEmail) {
    o.email = req.params.id;

    const hasEmail = m.hasEmail(o.email);
    if (hasEmail) {
      if (m.validatePassword(o.email, req.params.password)) {
        ret = await m.findByEmail(o.email);

        if (!ret) {
          res.json({
            code: 401,
            data: {},
            msg: "当前用户不存在",
          });
          return;
        }

        ret = ret.toObject();

        delete ret.password;

        res.json({
          code: 200,
          data: ret,
          msg: "success",
        });

        return;
      }

      res.json({
        code: pwderr.code,
        data: {},
        msg: pwderr.msg,
      });

      return;
    }
    res.json({
      code: notuser.code,
      data: {},
      msg: notuser.msg,
    });
    return;
  }

  if (isPhone) {
    o.phone = req.params.id;
    const hasPhone = m.hasPhone(o.phone);
    if (hasPhone) {
      ret = await m.findByPhone(o.phone);
      res.json({
        code: 200,
        data: ret,
        msg: "success",
      });
      return;
    }
    res.json({
      code: notuser.code,
      data: {},
      msg: notuser.msg,
    });
    return;
  }

  ret = await m.findById(req.params.id);
  res.json(ret);
});

router.post("/", async (req: Request, res: Response, next: NextFunction) => {
  const { phone, type } = req.body;

  const aim = phone;

  if (isPhone != type) {
    res.json({
      code: 200,
      data: {},
      msg: "获取失败",
    });
    return;
  }

  // code:String,
  // phone:String,
  // createTime:String,
  // expireTime:String
  const code = utils.getCode();
  const createTime = moment();
  const expireTime = moment().add(phoneCode.time, "s");
  const ret = await m.create({
    phone: aim,
    createTime: createTime.unix(),
    expireTime: expireTime.unix(),
    code,
  });

  await utils.sendMsg(aim, "发芽户外验证码", `您的验证码为${code}`);

  const data = {
    code,
    createTime: createTime.unix(),
    expireTime: expireTime.unix(),
  };

  if (!isDebug) {
    delete data.code;
  }

  res.json({
    code: 200,
    data,
    msg: "获取成功",
  });
});

router.put("/:id", function(req: Request, res: Response, next: NextFunction) {
  m.findByIdAndUpdate(req.params.id, req.body, function(err: any, post: any) {
    if (err) return next(err);
    res.json(post);
  });
});

router.delete("/:id", function(req: Request, res: Response, next: NextFunction) {
  m.findByIdAndRemove(req.params.id, req.body, function(err: any, post: any) {
    if (err) return next(err);
    res.json(post);
  });
});

module.exports = router;
